package org.typedtree


import _root_.v2.parser.cli.Commands
import _root_.v2.parser.load.Loader
import _root_.v2.parser.tree.{NodeCrud, TypedTree}
import _root_.v2.parser.{Literal, Type}
import eclipse.jetty.websocket.WebSocket
import eclipse.jetty.websocket.WebSocket.Outbound
import java.io.{StringWriter, OutputStreamWriter, File, IOException}
import util.parsing.input.CharSequenceReader

/**
 * @author bweber
 * @version $Rev$, $Date$
 */

class TypedTreeWebSocket (val typedTreeFile:String) extends WebSocket {
  var outbound: Outbound = null
  var commandParser: Commands = null
  var tree: NodeCrud = null

  def onConnect(outbound: Outbound) {
    this.outbound = outbound
    try {
      tree = NodeCrud(Loader(typedTreeFile).currentTree)
      commandParser = new Commands(tree)
      outbound.sendMessage(0.asInstanceOf[Byte], "successfully connected")
    }
    catch {
      case e: Exception => e.printStackTrace
    }
  }

  def onMessage(byte: Byte, str: String) {
    try {
      val writer = new StringWriter()
      commandParser.parseMore(new CharSequenceReader(str),writer)
      writer.write("\n")
      val result = writer.toString
      outbound.sendMessage(byte, result)
    }
    catch {
      case e: IOException => e.printStackTrace
    }
  }

  def onMessage(byte: Byte, bytes: Array[Byte], i: Int, i1: Int) {
    throw new RuntimeException("did not expect this version of onMessage to be called!")
  }

  def onDisconnect() {
    outbound.disconnect()
  }
}